import React from "react";
import "antd/dist/antd.css";
import {
  Button,
  Row,
  Card,
  Space,
  Drawer,
  Form,
  Col,
  Input,
  Select,
  DatePicker,
  Tooltip,
  message,
} from "antd";
import {
  PlusOutlined,
  MinusCircleOutlined,
  InfoCircleOutlined,
} from "@ant-design/icons";
import { Deliveryrecordadd, Goodsplantlist } from "../../../services/auth";
import moment from "moment";

const { Option } = Select;
function disabledDate(current) {
  // Can not select days before today and today
  return current < moment().startOf("day");
}

class DeliveryDrawer extends React.Component {
  constructor(props) {
    super(props);
    this.orderDetail = this.props.order;
    const { reset } = this.props;
    this.reset = reset;
    this.state = {
      visible: false,
      formInfo: {},
      plants: [],
      selectplant: 1,
    };
  }

  showDrawer = () => {
    this.setState({
      visible: true,
    });
    console.log(this.orderDetail);
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onSubmit = (values) => {
    let newArr = [];
    let sum = 0;
    for (let j = 0; j < values.delivery.length; j++) {
      let data = {
        plant_id: this.state.plants[values.delivery[j].plant].plant_id,
        quantity: values.delivery[j].quantity,
        date: values.delivery[j].date.format("YYYY-MM-DD"),
      };
      newArr.push(data);
      sum += parseInt(values.delivery[j].quantity);
    }
    if (this.orderDetail.quantity === sum) {
      console.log(newArr);
      // 正确才进行这个代码块中内容
      Deliveryrecordadd({
        id: this.orderDetail.id,
        goods_id: this.orderDetail.goods_id,
        deliveryRecord: newArr,
      }).then(
        (response) => {
          if (response.data === "success") {
            message.success("拣配成功");
            this.reset();
            this.onClose();
          } else {
            message.info("拣配失败，请重试");
          }
        },
        (error) => {
          console.log("数据获取失败", error);
        }
      );
    } else {
      message.error("请确保发货总数量等于订单需求量");
    }
  };

  deliverySubmit = () => {};

  componentDidMount() {
    Goodsplantlist(this.orderDetail.goods_id).then(
      (response) => {
        console.log(response.data);
        this.setState({
          plants: response.data,
        });
      },
      (error) => {
        console.log("err");
      }
    );
  }

  onSelect = (number) => {
    console.log(number);
    this.setState({
      selectplant: number,
    });
  };

  render() {
    return (
      <div className="drawer">
        <Button
          type="link"
          onClick={this.showDrawer}
          disabled={this.props.order.status !== "待发货"}
        >
          拣配
        </Button>
        <Drawer
          title="发货详情"
          width={720}
          onClose={this.onClose}
          visible={this.state.visible}
          bodyStyle={{ paddingBottom: 80 }}
        >
          <Form
            className="dynamic_form_nest_item"
            onFinish={this.onSubmit}
            autoComplete="off"
          >
            <Form.List name="delivery">
              {(fields, { add, remove }) => (
                <div>
                  {fields.map(({ key, name, fieldKey, ...restField }) => (
                    <Space
                      key={key}
                      style={{ display: "flex", width: "100%" }}
                      direction="vertical"
                    >
                      <Card>
                        <Row gutter={36}>
                          <Col span={16} style={{ textAlign: "left" }}>
                            <Form.Item
                              {...restField}
                              name={[name, "plant"]}
                              label="工厂"
                              fieldKey={[fieldKey, "plant"]}
                              rules={[
                                { required: true, message: "请选择发货工厂" },
                              ]}
                            >
                              <Select onSelect={this.onSelect}>
                                {this.state.plants.map((plant, index) => (
                                  <Option value={index}>
                                    {plant.plant_name}
                                  </Option>
                                ))}
                              </Select>
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={36}>
                          <Col span={16}>
                            <Form.Item
                              {...restField}
                              name={[name, "quantity"]}
                              label="数量"
                              fieldKey={[fieldKey, "quantity"]}
                              rules={[
                                { required: true, message: "请输入发货数量" },
                              ]}
                            >
                              <Input
                                suffix={
                                  <Tooltip
                                    title={`发货数量不能大于工厂库存${
                                      this.state.plants[this.state.selectplant]
                                        .quantity
                                    }`}
                                  >
                                    <InfoCircleOutlined
                                      style={{ color: "rgba(0,0,0,.45)" }}
                                    />
                                  </Tooltip>
                                }
                              />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={36}>
                          <Col span={16}>
                            <Form.Item
                              {...restField}
                              name={[name, "date"]}
                              label="日期"
                              fieldKey={[fieldKey, "date"]}
                              rules={[
                                { required: true, message: "请选择发货日期" },
                              ]}
                            >
                              <DatePicker
                                style={{ width: "100%" }}
                                disabledDate={disabledDate}
                              />
                            </Form.Item>
                          </Col>
                        </Row>
                        <Row gutter={36}>
                          <Col span={24}>
                            <Form.Item
                              {...restField}
                              name={[name, "description"]}
                              label="&nbsp;&nbsp;&nbsp;备注"
                              rules={[
                                {
                                  required: false,
                                  message: "...",
                                },
                              ]}
                            >
                              <Input.TextArea rows={4} placeholder="..." />
                            </Form.Item>
                          </Col>
                        </Row>
                      </Card>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      工厂
                    </Button>
                  </Form.Item>
                </div>
              )}
            </Form.List>
            <br />
            <br />
            <br />
            <Button htmlType="submit" type="primary">
              提交
            </Button>
          </Form>
        </Drawer>
      </div>
    );
  }
}

export default DeliveryDrawer;
